package com.scau402.system.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.scau402.common.annotation.DataScope;
import com.scau402.common.constant.DeptConstants;
import com.scau402.common.constant.InboundConstants;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.core.domain.entity.SysUser;
import com.scau402.common.exception.ServiceException;
import com.scau402.common.utils.Arith;
import com.scau402.common.utils.DateUtils;
import com.scau402.common.utils.SecurityUtils;
import com.scau402.common.utils.StringUtils;
import com.scau402.common.utils.code.InboundOrderCodeUtils;
import com.scau402.system.constants.SystemConstants;
import com.scau402.system.domain.*;
import com.scau402.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.scau402.system.mapper.WmsInboundOrderMapper;

/**
 * 商品入库单Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-26
 */
@Service
public class WmsInboundOrderServiceImpl implements IWmsInboundOrderService {
    @Autowired
    private WmsInboundOrderMapper wmsInboundOrderMapper;

    @Autowired
    private IWmsJadeService wmsJadeService;

    @Autowired
    private IWmsBasicSupplierService wmsBasicSupplierService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IWmsBasicClientService wmsBasicClientService;

    @Autowired
    private ISysTenantService tenantService;


    /**
     * 查询商品入库单
     *
     * @param id 商品入库单主键
     * @return 商品入库单
     */
    @Override
    public WmsInboundOrder selectWmsInboundOrderById(Long id) {
        return wmsInboundOrderMapper.selectWmsInboundOrderById(id);
    }

    /**
     * 查询商品入库单列表
     *
     * @param wmsInboundOrder 商品入库单
     * @return 商品入库单
     */
    @Override
    @DataScope(tenantAlias = "t", userAlias = "u")
    public List<WmsInboundOrder> selectWmsInboundOrderList(WmsInboundOrder wmsInboundOrder) {
        wmsInboundOrder.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        return wmsInboundOrderMapper.selectWmsInboundOrderList(wmsInboundOrder);
    }

    /**
     * 新增商品入库单
     *
     * @param wmsInboundOrder 商品入库单
     * @return 结果
     */
    @Override
    public int insertWmsInboundOrder(WmsInboundOrder wmsInboundOrder) {
        wmsInboundOrder.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        wmsInboundOrder.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        wmsInboundOrder.setCreateTime(DateUtils.getNowDate());
        wmsInboundOrder.setDeptId(DeptConstants.DEPT_ID_DEFAULT);
        return wmsInboundOrderMapper.insertWmsInboundOrder(wmsInboundOrder);
    }

    /**
     * 修改商品入库单
     *
     * @param wmsInboundOrder 商品入库单
     * @return 结果
     */
    @Override
    public int updateWmsInboundOrder(WmsInboundOrder wmsInboundOrder) {
        wmsInboundOrder.setTenantId(SecurityUtils.getLoginUser().getTenantId());
        wmsInboundOrder.setUpdateTime(DateUtils.getNowDate());
        wmsInboundOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        return wmsInboundOrderMapper.updateWmsInboundOrder(wmsInboundOrder);
    }

    /**
     * 批量删除商品入库单
     *
     * @param ids 需要删除的商品入库单主键
     * @return 结果
     */
    @Override
    public int deleteWmsInboundOrderByIds(Long[] ids) {
        List<Long> enabledIds=new ArrayList<>();
        for (Long id:ids) {
            WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectWmsInboundOrderById(id);
            String orderType = wmsInboundOrder.getOrderType();
            System.out.println(orderType);
            if (orderType.equals("2")||orderType.equals("3")){
                throw new ServiceException("只可删除采借入库的入库单");
            }else {
                enabledIds.add(id);
            }
        }
        Long[] idsArray = enabledIds.toArray(new Long[enabledIds.size()]);
        System.out.println(idsArray[0]);
        return wmsInboundOrderMapper.deleteWmsInboundOrderByIds(idsArray);
    }

    /**
     * 删除商品入库单信息
     *
     * @param id 商品入库单主键
     * @return 结果
     */
    @Override
    public int deleteWmsInboundOrderById(Long id) {
        WmsInboundOrder wmsInboundOrder = wmsInboundOrderMapper.selectWmsInboundOrderById(id);
        if (wmsInboundOrder.getOrderType().equals("2")||wmsInboundOrder.getOrderType().equals("3")){
            throw new ServiceException("只可删除采借入库的入库单");
        }
        return wmsInboundOrderMapper.deleteWmsInboundOrderById(id);
    }

    @Override
    public String getMaxCode(SysUser user) {
        Long tenantId = user.getTenantId();
        String userCode = user.getUserCode();
        userCode = userCode.substring(1);
        Map<String, Object> params = new HashMap<>();
        // 设置参数值
        params.put("tenantId", tenantId);
        params.put("userCode", userCode);
        return wmsInboundOrderMapper.getMaxCode(params);
    }

    /**
     * 获取入库单编码
     *
     * @param loginUserTenantCode
     * @param userCode
     * @return
     * @throws InterruptedException
     */
    @Override
    public String getInboundOrderCode(String loginUserTenantCode, String userCode) throws InterruptedException {
        InboundOrderCodeUtils inboundOrderCodeUtils = new InboundOrderCodeUtils();
        return inboundOrderCodeUtils.getNewCode(loginUserTenantCode, userCode);
    }

    /**
     * 根据入库单编码获取主键
     *
     * @param newOrderCode
     * @return
     */
    @Override
    public Long selectWmsInboundOrderIdByOrderCode(String newOrderCode) {
        return wmsInboundOrderMapper.selectWmsInboundOrderIdByOrderCode(newOrderCode);
    }

    @Override
    public WmsInboundOrder selectWmsInboundOrderByOrderCode(String orderCode) {
        return wmsInboundOrderMapper.selectWmsInboundOrderByOrderCode(orderCode);
    }

    @Override
    public int checkExists(WmsInboundOrder wmsInboundOrder) {
        return wmsInboundOrderMapper.checkExists(wmsInboundOrder);
    }

    /**
     * 检查suppliers中是否存在supplierId
     *
     * @param supplierId
     * @param suppliers
     * @return
     */
    @Override
    public boolean checkSupplierExist(Long supplierId, List<WmsBasicSupplier> suppliers) {
        for (WmsBasicSupplier supplier : suppliers) {
            if (supplier.getId().equals(supplierId)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public List<WmsInboundOrder> getDetails(List<WmsInboundOrder> list) {
        // 获取入库单翡翠数据
        for (WmsInboundOrder inboundOrder : list) {
            // 获取对应翡翠货品
            inboundOrder.setJades(wmsJadeService.selectJadesByOrderCode(inboundOrder));
            // 获取翡翠货品对应供应商列表
            List<WmsBasicSupplier> suppliers = new ArrayList<>();
            HashMap<Long, WmsBasicSupplier> supplierHashMap = new HashMap<>();
            // 获取翡翠货品对应客户列表
            List<WmsBasicClient> clients = new ArrayList<>();
            HashMap<Long, WmsBasicClient> clientHashMap = new HashMap<>();
            // 获取翡翠货品对应用户列表
            // List<SysUser> users = new ArrayList<>();

            for (WmsJade jade : inboundOrder.getJades()) {
                supplierHashMap.put(jade.getSupplierId(), wmsBasicSupplierService.selectWmsBasicSupplierById(jade.getSupplierId()));
                clientHashMap.put(jade.getClientId(), wmsBasicClientService.selectWmsBasicClientById(jade.getClientId()));
                // users.add(sysUserService.selectUserById(jade.))
            }
            for (WmsBasicSupplier supplier : supplierHashMap.values()) {
                suppliers.add(supplier);
            }
            for (WmsBasicClient client : clientHashMap.values()) {
                clients.add(client);
            }
            inboundOrder.setSuppliers(suppliers);
            inboundOrder.setClients(clients);
            // inboundOrder.setUsers(users); totalQuantity
        }
        return list;
    }

    /**
     * 获取订单借货数量
     * @param wmsInboundOrder
     * @return
     */
    @Override
    public Long getTotalBorrowQuantity(WmsInboundOrder wmsInboundOrder) {
        Long total = 0L;
        for(WmsJade jade : wmsInboundOrder.getJades()) {
            if(jade.getOrderType().equals(InboundConstants.INBOUND_ORDER_TYPE_BORROW)) {
                total += jade.getJadeQuantity();
            }
        }
        return total;
    }

    @Override
    public String getNewCode(SysUser user) throws InterruptedException {
        // 获取数据库中最大的编码
        String maxCode = getMaxCode(user);
        String userCode = user.getUserCode();

        // 返回maxCode为NULL，及当前数据库没有数据，从0开始
        if(StringUtils.isNull(maxCode)) {
            maxCode = InboundConstants.MAX_CODE_ZERO;
        }

        // 获取当前用户所属租户编码
        Long loginUserTenantId = SecurityUtils.getLoginUser().getTenantId();
        String loginUserTenantCode = tenantService.selectSysTenantByTenantId(loginUserTenantId).getTenantCode();

        // 设置redis的当前编码
        InboundOrderCodeUtils inboundOrderCodeUtils = new InboundOrderCodeUtils();
        inboundOrderCodeUtils.setCurrentCodeToMax(maxCode, loginUserTenantCode, userCode);
        return inboundOrderCodeUtils.getNewCode(loginUserTenantCode, userCode);
    }

}